
// 导入 axios 库
import axios from 'axios';
// 导入 useState 钩子(Hook)
import { useState } from 'react';
// 导入 useNavigate 钩子(Hook)
import { useNavigate } from 'react-router-dom';
// 导入 Ant Design 组件
import { Button, Form, Input, Radio, Select, DatePicker } from 'antd';

const { Option } = Select;

function LoongAddView(){

    const navigate = useNavigate();

    const [addLoongForm] = Form.useForm();

    const options = {
        labelCol: { span: 4 },
        wrapperCol: { span: 12 },
        autoComplete: "off",
    }

    const resetForm = () => {
        console.log( addLoongForm );
        addLoongForm.resetFields();
    }

    const onFinish = values => {
        console.log(values);
        let params = { ...values };
        // https://momentjs.com/
        let moment = params.birthdate;
        let value = moment.format('YYYY-MM-DD');
        params.birthdate = value;
        console.log( params );
        const promise = axios.put( '/back/loong/add' , params );
        promise.then( resp => {
            // 解构赋值 (这里使用的属性名与后端路由返回的JSON字符串相对应)
            let { success, message , result } = resp.data ;
            if( success ) {
                navigate( '/function/list' ); // 编程式导航
                return; // 让方法立即结束
            }
            console.log( message , result );
        }).catch( reason => {
            console.log( reason );
        })
    };

    return (
        <div className="add-loong-form-wrapper">
            <p>添加</p>
            <Form {...options} form={addLoongForm} onFinish={ onFinish }>
                <Form.Item label="姓名" name="name" rules={[ { required: true, message: '请输入姓名'}]}>
                    <Input />
                </Form.Item>
                <Form.Item label="性别" name="gender" rules={[ { required: true, message: '请选择性别'}]}>
                    <Radio.Group optionType="button" buttonStyle="solid" >
                        <Radio value="male">靓仔</Radio>
                        <Radio value="female">靓妹</Radio>
                    </Radio.Group>
                </Form.Item>
                <Form.Item label="出生日期" name="birthdate" rules={[ { required: true, message: '请选择日期'}]}>
                    <DatePicker style={ { width: '100%' } }/>
                </Form.Item>
                <Form.Item label="籍贯" name="hometown" rules={[ { required: true, message: '请选择籍贯'}]}>
                    <Select>
                        <Option value="东海">东海</Option>
                        <Option value="南海">南海</Option>
                        <Option value="西海">西海</Option>
                        <Option value="北海">北海</Option>
                    </Select>
                </Form.Item>
                <Form.Item wrapperCol={ { offset: 4, span: 12 } }>
                    <Button type="primary" htmlType="submit">添加</Button>
                    <Button htmlType="button" onClick={resetForm}>重置</Button>
                </Form.Item>
            </Form>
        </div> 
    )
}

export default LoongAddView;